<!DOCTYPE HTML>
<html lang="en" class="sidebar-visible no-js light">
    <head>
        <!-- Book generated using mdBook -->
        <meta charset="UTF-8">
        <title>part3_03_cache-in-ports - learning-gem5</title>
        <!-- Custom HTML head -->
        <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="theme-color" content="#ffffff" />

        <link rel="icon" href="../favicon.svg">
        <link rel="shortcut icon" href="../favicon.png">
        <link rel="stylesheet" href="../css/variables.css">
        <link rel="stylesheet" href="../css/general.css">
        <link rel="stylesheet" href="../css/chrome.css">
        <link rel="stylesheet" href="../css/print.css" media="print">
        <!-- Fonts -->
        <link rel="stylesheet" href="../FontAwesome/css/font-awesome.css">
        <link rel="stylesheet" href="../fonts/fonts.css">
        <!-- Highlight.js Stylesheets -->
        <link rel="stylesheet" href="../highlight.css">
        <link rel="stylesheet" href="../tomorrow-night.css">
        <link rel="stylesheet" href="../ayu-highlight.css">

        <!-- Custom theme stylesheets -->
    </head>
    <body>
        <!-- Provide site root to javascript -->
        <script type="text/javascript">
            var path_to_root = "../";
            var default_theme = window.matchMedia("(prefers-color-scheme: dark)").matches ? "navy" : "light";
        </script>

        <!-- Work around some values being stored in localStorage wrapped in quotes -->
        <script type="text/javascript">
            try {
                var theme = localStorage.getItem('mdbook-theme');
                var sidebar = localStorage.getItem('mdbook-sidebar');

                if (theme.startsWith('"') && theme.endsWith('"')) {
                    localStorage.setItem('mdbook-theme', theme.slice(1, theme.length - 1));
                }

                if (sidebar.startsWith('"') && sidebar.endsWith('"')) {
                    localStorage.setItem('mdbook-sidebar', sidebar.slice(1, sidebar.length - 1));
                }
            } catch (e) { }
        </script>

        <!-- Set the theme before any content is loaded, prevents flash -->
        <script type="text/javascript">
            var theme;
            try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { }
            if (theme === null || theme === undefined) { theme = default_theme; }
            var html = document.querySelector('html');
            html.classList.remove('no-js')
            html.classList.remove('light')
            html.classList.add(theme);
            html.classList.add('js');
        </script>

        <!-- Hide / unhide sidebar before it is displayed -->
        <script type="text/javascript">
            var html = document.querySelector('html');
            var sidebar = 'hidden';
            if (document.body.clientWidth >= 1080) {
                try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { }
                sidebar = sidebar || 'visible';
            }
            html.classList.remove('sidebar-visible');
            html.classList.add("sidebar-" + sidebar);
        </script>

        <nav id="sidebar" class="sidebar" aria-label="Table of contents">
            <div class="sidebar-scrollbox">
                <ol class="chapter"><li class="chapter-item expanded affix "><a href="../part0_introduction.html">Learning gem-5</a></li><li class="chapter-item expanded "><a href="../part0_introduction.html"><strong aria-hidden="true">1.</strong> part0_introduction</a></li><li class="chapter-item expanded "><a href="../part1/part1_1_building.html"><strong aria-hidden="true">2.</strong> part1</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../part1/part1_1_building.html"><strong aria-hidden="true">2.1.</strong> part1_1_building</a></li><li class="chapter-item expanded "><a href="../part1/part1_2_simple_config.html"><strong aria-hidden="true">2.2.</strong> part1_2_simple_config</a></li><li class="chapter-item expanded "><a href="../part1/part1_3_cache_config.html"><strong aria-hidden="true">2.3.</strong> part1_3_cache_config</a></li><li class="chapter-item expanded "><a href="../part1/part1_4_gem5_stats.html"><strong aria-hidden="true">2.4.</strong> part1_4_gem5_stats</a></li><li class="chapter-item expanded "><a href="../part1/part1_5_gem5_example_configs.html"><strong aria-hidden="true">2.5.</strong> part1_5_gem5_example_configs</a></li><li class="chapter-item expanded "><a href="../part1/part1_6_extending_configs.html"><strong aria-hidden="true">2.6.</strong> part1_6_extending_configs</a></li></ol></li><li class="chapter-item expanded "><a href="../part2/part2_0_environment.html"><strong aria-hidden="true">3.</strong> part2</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../part2/part2_0_environment.html"><strong aria-hidden="true">3.1.</strong> part2_0_environment</a></li><li class="chapter-item expanded "><a href="../part2/part2_1_helloobject.html"><strong aria-hidden="true">3.2.</strong> part2_1_helloobject</a></li><li class="chapter-item expanded "><a href="../part2/part2_2_debugging.html"><strong aria-hidden="true">3.3.</strong> part2_2_debugging</a></li><li class="chapter-item expanded "><a href="../part2/part2_3_events.html"><strong aria-hidden="true">3.4.</strong> part2_3_events</a></li><li class="chapter-item expanded "><a href="../part2/part2_4_parameters.html"><strong aria-hidden="true">3.5.</strong> part2_4_parameters</a></li><li class="chapter-item expanded "><a href="../part2/part2_5_memoryobject.html"><strong aria-hidden="true">3.6.</strong> part2_5_memoryobject</a></li><li class="chapter-item expanded "><a href="../part2/part2_6_simplecache.html"><strong aria-hidden="true">3.7.</strong> part2_6_simplecache</a></li><li class="chapter-item expanded "><a href="../part2/part2_7_arm_power_modelling.html"><strong aria-hidden="true">3.8.</strong> part2_7_arm_power_modelling</a></li><li class="chapter-item expanded "><a href="../part2/part2_8_arm_dvfs_support.html"><strong aria-hidden="true">3.9.</strong> part2_8_arm_dvfs_support</a></li></ol></li><li class="chapter-item expanded "><a href="../part3/part3_00_MSIntro.html"><strong aria-hidden="true">4.</strong> part3</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../part3/part3_00_MSIntro.html"><strong aria-hidden="true">4.1.</strong> part3_00_MSIntro</a></li><li class="chapter-item expanded "><a href="../part3/part3_01_cache-intro.html"><strong aria-hidden="true">4.2.</strong> part3_01_cache-intro</a></li><li class="chapter-item expanded "><a href="../part3/part3_02_cache-declarations.html"><strong aria-hidden="true">4.3.</strong> part3_02_cache-declarations</a></li><li class="chapter-item expanded "><a href="../part3/part3_03_cache-in-ports.html" class="active"><strong aria-hidden="true">4.4.</strong> part3_03_cache-in-ports</a></li><li class="chapter-item expanded "><a href="../part3/part3_04_cache_actions.html"><strong aria-hidden="true">4.5.</strong> part3_04_cache_actions</a></li><li class="chapter-item expanded "><a href="../part3/part3_05_cache_transitions.html"><strong aria-hidden="true">4.6.</strong> part3_05_cache_transitions</a></li><li class="chapter-item expanded "><a href="../part3/part3_06_directory.html"><strong aria-hidden="true">4.7.</strong> part3_06_directory</a></li><li class="chapter-item expanded "><a href="../part3/part3_07_MSIbuilding.html"><strong aria-hidden="true">4.8.</strong> part3_07_MSIbuilding</a></li><li class="chapter-item expanded "><a href="../part3/part3_08_configuration.html"><strong aria-hidden="true">4.9.</strong> part3_08_configuration</a></li><li class="chapter-item expanded "><a href="../part3/part3_09_running.html"><strong aria-hidden="true">4.10.</strong> part3_09_running</a></li><li class="chapter-item expanded "><a href="../part3/part3_10_MSIdebugging.html"><strong aria-hidden="true">4.11.</strong> part3_10_MSIdebugging</a></li><li class="chapter-item expanded "><a href="../part3/part3_11_simple-MI_example.html"><strong aria-hidden="true">4.12.</strong> part3_11_simple-MI_example</a></li></ol></li><li class="chapter-item expanded "><a href="../part4_gem5_101.html"><strong aria-hidden="true">5.</strong> part4_gem5_101</a></li><li class="chapter-item expanded "><a href="../http://doxygen.gem5.org/develop/index.html"><strong aria-hidden="true">6.</strong> part4_gem5_102</a></li></ol>
            </div>
            <div id="sidebar-resize-handle" class="sidebar-resize-handle"></div>
        </nav>

        <div id="page-wrapper" class="page-wrapper">

            <div class="page">
                <div id="menu-bar-hover-placeholder"></div>
                <div id="menu-bar" class="menu-bar sticky bordered">
                    <div class="left-buttons">
                        <button id="sidebar-toggle" class="icon-button" type="button" title="Toggle Table of Contents" aria-label="Toggle Table of Contents" aria-controls="sidebar">
                            <i class="fa fa-bars"></i>
                        </button>
                        <button id="theme-toggle" class="icon-button" type="button" title="Change theme" aria-label="Change theme" aria-haspopup="true" aria-expanded="false" aria-controls="theme-list">
                            <i class="fa fa-paint-brush"></i>
                        </button>
                        <ul id="theme-list" class="theme-popup" aria-label="Themes" role="menu">
                            <li role="none"><button role="menuitem" class="theme" id="light">Light (default)</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="rust">Rust</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="coal">Coal</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="navy">Navy</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="ayu">Ayu</button></li>
                        </ul>
                        <button id="search-toggle" class="icon-button" type="button" title="Search. (Shortkey: s)" aria-label="Toggle Searchbar" aria-expanded="false" aria-keyshortcuts="S" aria-controls="searchbar">
                            <i class="fa fa-search"></i>
                        </button>
                    </div>

                    <h1 class="menu-title">learning-gem5</h1>

                    <div class="right-buttons">
                        <a href="../print.html" title="Print this book" aria-label="Print this book">
                            <i id="print-button" class="fa fa-print"></i>
                        </a>
                    </div>
                </div>

                <div id="search-wrapper" class="hidden">
                    <form id="searchbar-outer" class="searchbar-outer">
                        <input type="search" id="searchbar" name="searchbar" placeholder="Search this book ..." aria-controls="searchresults-outer" aria-describedby="searchresults-header">
                    </form>
                    <div id="searchresults-outer" class="searchresults-outer hidden">
                        <div id="searchresults-header" class="searchresults-header"></div>
                        <ul id="searchresults">
                        </ul>
                    </div>
                </div>
                <!-- Apply ARIA attributes after the sidebar and the sidebar toggle button are added to the DOM -->
                <script type="text/javascript">
                    document.getElementById('sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible');
                    document.getElementById('sidebar').setAttribute('aria-hidden', sidebar !== 'visible');
                    Array.from(document.querySelectorAll('#sidebar a')).forEach(function(link) {
                        link.setAttribute('tabIndex', sidebar === 'visible' ? 0 : -1);
                    });
                </script>

                <div id="content" class="content">
                    <main>
                        <hr />
<h2>layout: documentation
title: In port code blocks
doc: Learning gem5
parent: part3
permalink: documentation/learning_gem5/part3/cache-in-ports/
author: Jason Lowe-Power</h2>
<h1 id="in-port-code-blocks"><a class="header" href="#in-port-code-blocks">In port code blocks</a></h1>
<p>After declaring all of the structures we need in the state machine file,
the first &quot;functional&quot; part of the file are the &quot;in ports&quot;. This section
specifies what <em>events</em> to <em>trigger</em> on different incoming messages.</p>
<p>However, before we get to the in ports, we must declare our out ports.</p>
<pre><code class="language-cpp">out_port(request_out, RequestMsg, requestToDir);
out_port(response_out, ResponseMsg, responseToDirOrSibling);
</code></pre>
<p>This code essentially just renames <code>requestToDir</code> and
<code>responseToDirOrSibling</code> to <code>request_out</code> and <code>response_out</code>. Later in
the file, when we want to <em>enqueue</em> messages to these message buffers we
will use the new names <code>request_out</code> and <code>response_out</code>. This also
specifies the exact implementation of the messages that we will send
across these ports. We will look at the exact definition of these types
below in the file <code>MSI-msg.sm</code>.</p>
<p>Next, we create an <em>in port code block</em>. In SLICC, there are many cases
where there are code blocks that look similar to <code>if</code> blocks, but they
encode specific information. For instance, the code inside an
<code>in_port()</code> block is put in a special generated file:
<code>L1Cache_Wakeup.cc</code>.</p>
<p>All of the <code>in_port</code> code blocks are executed in order (or based on the
priority if it is specified). On each active cycle for the controller,
the first <code>in_port</code> code is executed. If it is successful, it is
re-executed to see if there are other messages that can be consumed on
the port. If there are no messages or no events are triggered, then the
next <code>in_port</code> code block is executed.</p>
<p>There are three different kinds of <em>stalls</em> that can be generated when
executing <code>in_port</code> code blocks. First, there is a parameterized limit
for the number of transitions per cycle at each controller. If this
limit is reached (i.e., there are more messages on the message buffers
than the transition per cycle limit), then all <code>in_port</code> will stop
processing and wait to continue until the next cycle. Second, there
could be a <em>resource stall</em>. This happens if some needed resource is
unavailable. For instance, if using the <code>BankedArray</code> bandwidth model,
the needed bank of the cache may be currently occupied. Third, there
could be a <em>protocol stall</em>. This is a special kind of action that
causes the state machine to stall until the next cycle.</p>
<p>It is important to note that protocol stalls and resource stalls prevent
<strong>all</strong> <code>in_port</code> blocks from executing. For instance, if the first
<code>in_port</code> block generates a protocol stall, none of the other ports will
be executed, blocking all messages. This is why it is important to use
the correct number and ordering of virtual networks.</p>
<p>Below, is the full code for the <code>in_port</code> block for the highest priority
messages to our L1 cache controller, the response from directory or
other caches. Next we will break the code block down to explain each
section.</p>
<pre><code class="language-cpp">in_port(response_in, ResponseMsg, responseFromDirOrSibling) {
    if (response_in.isReady(clockEdge())) {
        peek(response_in, ResponseMsg) {
            Entry cache_entry := getCacheEntry(in_msg.addr);
            TBE tbe := TBEs[in_msg.addr];
            assert(is_valid(tbe));

            if (machineIDToMachineType(in_msg.Sender) ==
                        MachineType:Directory) {
                if (in_msg.Type != CoherenceResponseType:Data) {
                    error(&quot;Directory should only reply with data&quot;);
                }
                assert(in_msg.Acks + tbe.AcksOutstanding &gt;= 0);
                if (in_msg.Acks + tbe.AcksOutstanding == 0) {
                    trigger(Event:DataDirNoAcks, in_msg.addr, cache_entry,
                            tbe);
                } else {
                    trigger(Event:DataDirAcks, in_msg.addr, cache_entry,
                            tbe);
                }
            } else {
                if (in_msg.Type == CoherenceResponseType:Data) {
                    trigger(Event:DataOwner, in_msg.addr, cache_entry,
                            tbe);
                } else if (in_msg.Type == CoherenceResponseType:InvAck) {
                    DPRINTF(RubySlicc, &quot;Got inv ack. %d left\n&quot;,
                            tbe.AcksOutstanding);
                    if (tbe.AcksOutstanding == 1) {
                        trigger(Event:LastInvAck, in_msg.addr, cache_entry,
                                tbe);
                    } else {
                        trigger(Event:InvAck, in_msg.addr, cache_entry,
                                tbe);
                    }
                } else {
                    error(&quot;Unexpected response from other cache&quot;);
                }
            }
        }
    }
}
</code></pre>
<p>First, like the out_port above &quot;response_in&quot; is the name we'll use
later when we refer to this port, and &quot;ResponseMsg&quot; is the type of
message we expect on this port (since this port processes responses to
our requests). The first step in all <code>in_port</code> code blocks is to check
the message buffer to see if there are any messages to be processed. If
not, then this <code>in_port</code> code block is skipped and the next one is
executed.</p>
<pre><code class="language-cpp">in_port(response_in, ResponseMsg, responseFromDirOrSibling) {
    if (response_in.isReady(clockEdge())) {
        . . .
    }
}
</code></pre>
<p>Assuming there is a valid message in the message buffer, next, we grab
that message by using the special code block <code>peek</code>. Peek is a special
function. Any code inside a peek statement has a special variable
declared and populated: <code>in_msg</code>. This contains the message (of type
ResponseMsg in this case as specified by the second parameter of the
<code>peek</code> call) at the head of the port. Here, <code>response_in</code> is the port we
want to peek into.</p>
<p>Then, we need to grab the cache entry and the TBE for the incoming
address. (We will look at the other parameters in response message
below.) Above, we implemented getCacheEntry. It will return either the
valid matching entry for the address, or an invalid entry if there is
not a matching cache block.</p>
<p>For the TBE, since this is a response to a request this cache controller
initiated, there <em>must</em> be a valid TBE in the TBE table. Hence, we see
our first debug statement, an <em>assert</em>. This is one of the ways to ease
debugging of cache coherence protocols. It is encouraged to use asserts
liberally to make debugging easier.</p>
<pre><code class="language-cpp">peek(response_in, ResponseMsg) {
    Entry cache_entry := getCacheEntry(in_msg.addr);
    TBE tbe := TBEs[in_msg.addr];
    assert(is_valid(tbe));

    . . .
}
</code></pre>
<p>Next, we need to decide what event to trigger based on the message. For
this, we first need to discuss what data response messages are carrying.</p>
<p>To declare a new message type, first create a new file for all of the
message types: <code>MSI-msg.sm</code>. In this file, you can declare any
structures that will be <em>globally</em> used across all of the SLICC files
for your protocol. We will include this file in all of the state machine
definitions via the <code>MSI.slicc</code> file later. This is similar to including
global definitions in header files in C/C++.</p>
<p>In the <code>MSI-msg.sm</code> file, add the following code block:</p>
<pre><code class="language-cpp">structure(ResponseMsg, desc=&quot;Used for Dir-&gt;Cache and Fwd message responses&quot;,
          interface=&quot;Message&quot;) {
    Addr addr,                   desc=&quot;Physical address for this response&quot;;
    CoherenceResponseType Type,  desc=&quot;Type of response&quot;;
    MachineID Sender,            desc=&quot;Node who is responding to the request&quot;;
    NetDest Destination,         desc=&quot;Multicast destination mask&quot;;
    DataBlock DataBlk,           desc=&quot;data for the cache line&quot;;
    MessageSizeType MessageSize, desc=&quot;size category of the message&quot;;
    int Acks,                    desc=&quot;Number of acks required from others&quot;;

    // This must be overridden here to support functional accesses
    bool functionalRead(Packet *pkt) {
        if (Type == CoherenceResponseType:Data) {
            return testAndRead(addr, DataBlk, pkt);
        }
        return false;
    }

    bool functionalWrite(Packet *pkt) {
        // No check on message type required since the protocol should read
        // data block from only those messages that contain valid data
        return testAndWrite(addr, DataBlk, pkt);
    }
}
</code></pre>
<p>The message is just another SLICC structure similar to the structures
we've defined before. However, this time, we have a specific interface
that it is implementing: <code>Message</code>. Within this message, we can add any
members that we need for our protocol. In this case, we first have the
address. Note, a common &quot;gotcha&quot; is that you <em>cannot</em> use &quot;Addr&quot; with a
capitol &quot;A&quot; for the name of the member since it is the same name as the
type!</p>
<p>Next, we have the type of response. In our case, there are two types of
response data and invalidation acks from other caches after they have
invalidated their copy. Thus, we need to define an <em>enumeration</em>, the
<code>CoherenceResponseType</code>, to use it in this message. Add the following
code <em>before</em> the <code>ResponseMsg</code> declaration in the same file.</p>
<pre><code class="language-cpp">enumeration(CoherenceResponseType, desc=&quot;Types of response messages&quot;) {
    Data,       desc=&quot;Contains the most up-to-date data&quot;;
    InvAck,     desc=&quot;Message from another cache that they have inv. the blk&quot;;
}
</code></pre>
<p>Next, in the response message type, we have the <code>MachineID</code> which sent
the response. <code>MachineID</code> is the <em>specific machine</em> that sent the
response. For instance, it might be directory 0 or cache 12. The
<code>MachineID</code> contains both the <code>MachineType</code> (e.g., we have been creating
an <code>L1Cache</code> as declared in the first <code>machine()</code>) and the specific
<em>version</em> of that machine type. We will come back to machine version
numbers when configuring the system.</p>
<p>Next, all messages need a <em>destination</em>, and a <em>size</em>. The destination
is specified as a <code>NetDest</code>, which is a bitmap of all the <code>MachineID</code> in
the system. This allows messages to be broadcast to a flexible set of
receivers. The message also has a size. You can find the possible
message sizes in <code>src/mem/protocol/RubySlicc_Exports.sm</code>.</p>
<p>This message may also contain a data block and the number acks that are
expected. Thus, we can include these in the message definition as well.</p>
<p>Finally, we also have to define functional read and write functions.
These are used by Ruby to inspect in-flight messages on function reads
and writes. Note: This functionality currently is very brittle and if
there are messages in-flight for an address that is functionally read or
written the functional access may fail.</p>
<p>You can download the complete <code>MSI-msg.sm</code> file 
<a href="/_pages/static/scripts/part3/MSI_protocol/MSI-msg.sm">here</a>.</p>
<p>Now that we have defined the data in the response message, we can look
at how we choose which action to trigger in the <code>in_port</code> for response
to the cache.</p>
<pre><code class="language-cpp">// If it's from the directory...
if (machineIDToMachineType(in_msg.Sender) ==
            MachineType:Directory) {
    if (in_msg.Type != CoherenceResponseType:Data) {
        error(&quot;Directory should only reply with data&quot;);
    }
    assert(in_msg.Acks + tbe.AcksOutstanding &gt;= 0);
    if (in_msg.Acks + tbe.AcksOutstanding == 0) {
        trigger(Event:DataDirNoAcks, in_msg.addr, cache_entry,
                tbe);
    } else {
        trigger(Event:DataDirAcks, in_msg.addr, cache_entry,
                tbe);
    }
} else {
    // This is from another cache.
    if (in_msg.Type == CoherenceResponseType:Data) {
        trigger(Event:DataOwner, in_msg.addr, cache_entry,
                tbe);
    } else if (in_msg.Type == CoherenceResponseType:InvAck) {
        DPRINTF(RubySlicc, &quot;Got inv ack. %d left\n&quot;,
                tbe.AcksOutstanding);
        if (tbe.AcksOutstanding == 1) {
            // If there is exactly one ack remaining then we
            // know it is the last ack.
            trigger(Event:LastInvAck, in_msg.addr, cache_entry,
                    tbe);
        } else {
            trigger(Event:InvAck, in_msg.addr, cache_entry,
                    tbe);
        }
    } else {
        error(&quot;Unexpected response from other cache&quot;);
    }
}
</code></pre>
<p>First, we check to see if the message comes from the directory or
another cache. If it comes from the directory, we know that it <em>must</em> be
a data response (the directory will never respond with an ack).</p>
<p>Here, we meet our second way to add debug information to protocols: the
<code>error</code> function. This function breaks simulation and prints out the
string parameter similar to <code>panic</code>.</p>
<p>Next, when we receive data from the directory, we expect that the number
of acks we are waiting for will never be less than 0. The number of acks
we're waiting for is the current acks we have received
(tbe.AcksOutstanding) and the number of acks the directory has told us
to be waiting for. We need to check it this way because it is possible
that we have received acks from other caches before we get the message
from the directory that we need to wait for acks.</p>
<p>There are two possibilities for the acks, either we have already
received all of the acks and now we are getting the data (data from dir
acks==0 in Table 8.3), or we need to wait for more acks. Thus, we check
this condition and trigger two different events, one for each
possibility.</p>
<p>When triggering transitions, you need to pass four parameters. The first
parameter is the event to trigger. These events were specified earlier
in the <code>Event</code> declaration. The next parameter is the (physical memory)
address of the cache block to operate on. Usually this is the same as
the address of the <code>in_msg</code>, but it may be different, for instance, on a
replacement the address is for the block being replaced. Next is the
cache entry and the TBE for the block. These may be invalid if there are
no valid entries for the address in the cache or there is not a valid
TBE in the TBE table.</p>
<p>When we implement actions below, we will see how these last three
parameters are used. They are passed into the actions as implicit
variables: <code>address</code>, <code>cache_entry</code>, and <code>tbe</code>.</p>
<p>If the <code>trigger</code> function is executed, after the transition is complete,
the <code>in_port</code> logic is executed again, assuming there have been fewer
transitions than that maximum transitions per cycle. If there are other
messages in the message buffer more transitions can be triggered.</p>
<p>If the response is from another cache instead of the directory, then
other events are triggered, as shown in the code above. These events
come directly from Table 8.3 in Sorin et al.</p>
<p>Importantly, you should use the <code>in_port</code> logic to check all conditions.
After an event is triggered, it should only have a <em>single code path</em>.
I.e., there should be no <code>if</code> statements in any action blocks. If you
want to conditionally execute actions, you should use different states
or different events in the <code>in_port</code> logic.</p>
<p>The reason for this constraint is the way Ruby checks resources before
executing a transition. In the generated code from the <code>in_port</code> blocks
before the transition is actually executed all of the resources are
checked. In other words, transitions are atomic and either execute all
of the actions or none. Conditional statements inside the actions
prevents the SLICC compiler from correctly tracking the resource usage
and can lead to strange performance, deadlocks, and other bugs.</p>
<p>After specifying the <code>in_port</code> logic for the highest priority network,
the response network, we need to add the <code>in_port</code> logic for the forward
request network. However, before specifying this logic, we need to
define the <code>RequestMsg</code> type and the <code>CoherenceRequestType</code> which
contains the types of requests. These two definitions go in the
<code>MSI-msg.sm</code> file <em>not in MSI-cache.sm</em> since they are global
definitions.</p>
<p>It is possible to implement this as two different messages and request
type enumerations, one for forward and one for normal requests, but it
simplifies the code to use a single message and type.</p>
<pre><code class="language-cpp">enumeration(CoherenceRequestType, desc=&quot;Types of request messages&quot;) {
    GetS,       desc=&quot;Request from cache for a block with read permission&quot;;
    GetM,       desc=&quot;Request from cache for a block with write permission&quot;;
    PutS,       desc=&quot;Sent to directory when evicting a block in S (clean WB)&quot;;
    PutM,       desc=&quot;Sent to directory when evicting a block in M&quot;;

    // &quot;Requests&quot; from the directory to the caches on the fwd network
    Inv,        desc=&quot;Probe the cache and invalidate any matching blocks&quot;;
    PutAck,     desc=&quot;The put request has been processed.&quot;;
}
</code></pre>
<pre><code class="language-cpp">structure(RequestMsg, desc=&quot;Used for Cache-&gt;Dir and Fwd messages&quot;,  interface=&quot;Message&quot;) {
    Addr addr,                   desc=&quot;Physical address for this request&quot;;
    CoherenceRequestType Type,   desc=&quot;Type of request&quot;;
    MachineID Requestor,         desc=&quot;Node who initiated the request&quot;;
    NetDest Destination,         desc=&quot;Multicast destination mask&quot;;
    DataBlock DataBlk,           desc=&quot;data for the cache line&quot;;
    MessageSizeType MessageSize, desc=&quot;size category of the message&quot;;

    bool functionalRead(Packet *pkt) {
        // Requests should never have the only copy of the most up-to-date data
        return false;
    }

    bool functionalWrite(Packet *pkt) {
        // No check on message type required since the protocol should read
        // data block from only those messages that contain valid data
        return testAndWrite(addr, DataBlk, pkt);
    }
}
</code></pre>
<p>Now, we can specify the logic for the forward network <code>in_port</code>. This
logic is straightforward and triggers a different event for each request
type.</p>
<pre><code class="language-cpp">in_port(forward_in, RequestMsg, forwardFromDir) {
    if (forward_in.isReady(clockEdge())) {
        peek(forward_in, RequestMsg) {
            // Grab the entry and tbe if they exist.
            Entry cache_entry := getCacheEntry(in_msg.addr);
            TBE tbe := TBEs[in_msg.addr];

            if (in_msg.Type == CoherenceRequestType:GetS) {
                trigger(Event:FwdGetS, in_msg.addr, cache_entry, tbe);
            } else if (in_msg.Type == CoherenceRequestType:GetM) {
                trigger(Event:FwdGetM, in_msg.addr, cache_entry, tbe);
            } else if (in_msg.Type == CoherenceRequestType:Inv) {
                trigger(Event:Inv, in_msg.addr, cache_entry, tbe);
            } else if (in_msg.Type == CoherenceRequestType:PutAck) {
                trigger(Event:PutAck, in_msg.addr, cache_entry, tbe);
            } else {
                error(&quot;Unexpected forward message!&quot;);
            }
        }
    }
}
</code></pre>
<p>The final <code>in_port</code> is for the mandatory queue. This is the lowest
priority queue, so it must be lowest in the state machine file. The
mandatory queue has a special message type: <code>RubyRequest</code>. This type is
specified in <code>src/mem/protocol/RubySlicc_Types.sm</code> It contains two
different addresses, the <code>LineAddress</code> which is cache-block aligned and
the <code>PhysicalAddress</code> which holds the original request's address and may
not be cache-block aligned. It also has other members that may be useful
in some protocols. However, for this simple protocol we only need the
<code>LineAddress</code>.</p>
<pre><code class="language-cpp">in_port(mandatory_in, RubyRequest, mandatoryQueue) {
    if (mandatory_in.isReady(clockEdge())) {
        peek(mandatory_in, RubyRequest, block_on=&quot;LineAddress&quot;) {
            Entry cache_entry := getCacheEntry(in_msg.LineAddress);
            TBE tbe := TBEs[in_msg.LineAddress];

            if (is_invalid(cache_entry) &amp;&amp;
                    cacheMemory.cacheAvail(in_msg.LineAddress) == false ) {
                Addr addr := cacheMemory.cacheProbe(in_msg.LineAddress);
                Entry victim_entry := getCacheEntry(addr);
                TBE victim_tbe := TBEs[addr];
                trigger(Event:Replacement, addr, victim_entry, victim_tbe);
            } else {
                if (in_msg.Type == RubyRequestType:LD ||
                        in_msg.Type == RubyRequestType:IFETCH) {
                    trigger(Event:Load, in_msg.LineAddress, cache_entry,
                            tbe);
                } else if (in_msg.Type == RubyRequestType:ST) {
                    trigger(Event:Store, in_msg.LineAddress, cache_entry,
                            tbe);
                } else {
                    error(&quot;Unexpected type from processor&quot;);
                }
            }
        }
    }
}
</code></pre>
<p>There are a couple of new concepts shown in this code block. First, we
use <code>block_on=&quot;LineAddress&quot;</code> in the peek function. What this does is
ensure that any other requests to the same cache line will be blocked
until the current request is complete.</p>
<p>Next, we check if the cache entry for this line is valid. If not, and
there are no more entries available in the set, then we need to evict
another entry. To get the victim address, we can use the <code>cacheProbe</code>
function on the <code>CacheMemory</code> object. This function uses the
parameterized replacement policy and returns the physical (line) address
of the victim.</p>
<p>Importantly, when we trigger the <code>Replacement</code> event <em>we use the address
of the victim block</em> and the victim cache entry and tbe. Thus, when we
take actions in the replacement transitions we will be acting on the
victim block, not the requesting block. Additionally, we need to
remember to <em>not</em> remove the requesting message from the mandatory queue
(pop) until it has been satisfied. The message should not be popped
after the replacement is complete.</p>
<p>If the cache block was found to be valid, then we simply trigger the
<code>Load</code> or <code>Store</code> event.</p>

                    </main>

                    <nav class="nav-wrapper" aria-label="Page navigation">
                        <!-- Mobile navigation buttons -->
                            <a rel="prev" href="../part3/part3_02_cache-declarations.html" class="mobile-nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
                                <i class="fa fa-angle-left"></i>
                            </a>
                            <a rel="next" href="../part3/part3_04_cache_actions.html" class="mobile-nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
                                <i class="fa fa-angle-right"></i>
                            </a>
                        <div style="clear: both"></div>
                    </nav>
                </div>
            </div>

            <nav class="nav-wide-wrapper" aria-label="Page navigation">
                    <a rel="prev" href="../part3/part3_02_cache-declarations.html" class="nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
                        <i class="fa fa-angle-left"></i>
                    </a>
                    <a rel="next" href="../part3/part3_04_cache_actions.html" class="nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
                        <i class="fa fa-angle-right"></i>
                    </a>
            </nav>

        </div>

        <script type="text/javascript">
            window.playground_copyable = true;
        </script>
        <script src="../elasticlunr.min.js" type="text/javascript" charset="utf-8"></script>
        <script src="../mark.min.js" type="text/javascript" charset="utf-8"></script>
        <script src="../searcher.js" type="text/javascript" charset="utf-8"></script>
        <script src="../clipboard.min.js" type="text/javascript" charset="utf-8"></script>
        <script src="../highlight.js" type="text/javascript" charset="utf-8"></script>
        <script src="../book.js" type="text/javascript" charset="utf-8"></script>

        <!-- Custom JS scripts -->
    </body>
</html>
